package com.itboye.eweilisten.me.login;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.generic.RoundingParams;
import com.itboye.eweilisten.R;
import com.itboye.eweilisten.base.BaseActivity;
import com.itboye.eweilisten.common.MyEditText;
import com.itboye.eweilisten.main.MainActivity;
import com.itboye.eweilisten.me.personal.activity.WebActivity;
import com.itboye.eweilisten.me.personal.model.PersonDataBean;
import com.itboye.eweilisten.presenter.UserPresenter;
import com.itboye.eweilisten.util.dbutil.UserListManager;
import com.itboye.eweilisten.util.loadingutil.MAlert;
import com.itboye.eweilisten.util.sputil.Const;
import com.itboye.eweilisten.util.sputil.MyPermission;
import com.itboye.eweilisten.util.sputil.SPUtils;
import com.itboye.eweilisten.util.widget.EmailAutoCompleteTextView;
import com.itboye.eweilisten.util.widget.FilterUtil;
import com.itboye.eweilisten.util.widget.IsStringSPUtils;
import com.itboye.eweilisten.volley.ResultEntity;

import java.util.Observable;
import java.util.Observer;

/**
 * 通过手机号登陆
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener, Observer {

    TextView txt_forgetpwd, txt_register, tvTest;
    Button login_phone_ok, login_phone_login;
    MyEditText login_pwd;
    TextView tvTitle;
    EmailAutoCompleteTextView login_phone;
    ImageView back;
    private UserPresenter userPresenter;
    UserListManager userListManager;
    private CheckBox checkboxLgoin = null;
    boolean isChecked = false;
    String phone;
    SharedPreferences sp = null;
    private TextView textView;
    private static final int REQUEST_CODE = 0; // 请求码
    boolean Main=false;

    public static String LOGIN = "com.itboye.eweilisten.login";// 登录的广播
    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.MODIFY_AUDIO_SETTINGS
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        setContentView(R.layout.activity_login_to_phone);
        Main=getIntent().getBooleanExtra("main",false);
        RoundingParams roundingParams = RoundingParams.fromCornersRadius(5f);
        roundingParams.setBorder(getResources().getColor(R.color.red), 1.0f);
        roundingParams.setRoundAsCircle(true);
        MyPermission.CheckPermission(this, Manifest.permission.READ_PHONE_STATE);
        userListManager = new UserListManager(this);
        tvTitle.setText("登录");
        tvTest.setText("注册");
        tvTest.setTextColor(getResources().getColor(R.color.white));
        tvTest.setVisibility(View.VISIBLE);
        userPresenter = new UserPresenter(this);

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(login_phone.getWindowToken(), 0);
        init();
    }


    private void init() {
        sp = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        //判断记住密码多选框的状态
        if (sp.getBoolean("checkboxBoolean", true)) {
            login_phone.setText(sp.getString("uname", null));
            login_pwd.setText(sp.getString("pwd", null));
            checkboxLgoin.setChecked(true);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.login_phone_ok:
                phone = login_phone.getText().toString();
                String pwd = login_pwd.getText().toString();
                if (phone.equals("")) {
                    MAlert.alert("请输入账号", Gravity.TOP);
                    return;
                }
                if (pwd.equals("")) {
                    MAlert.alert("请输入密码", Gravity.TOP);
                    return;
                } else if (pwd.length() != 6) {
                    MAlert.alert("请输入6位数字密码");
                    return;
                }
                showProgressDialog("登录中,请稍后", true);
                Log.d("werwerwerwe", phone + "" + pwd);

                userPresenter.login(phone, pwd);
                onShared(phone, pwd);
                break;
            case R.id.back:
                finish();
                break;
            case R.id.txt_forgetpwd:
                intent = new Intent(this, ForgetPassWord.class);
                startActivityForResult(intent, 101);
                break;
            case R.id.tvTest:
                intent = new Intent(this, RegisterActivity.class);
                startActivityForResult(intent, 101);
                break;
            case R.id.textView:
                intent = new Intent(this, WebActivity.class);
                intent.putExtra("title", "遇到问题");
                intent.putExtra("url", Const.WEB + "web/helper");
                startActivity(intent);
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == 101) {
            Bundle b = data.getExtras();
            String name = b.getString("eimal");
            Log.d("eimaleimal", name);
        }
        if (requestCode == REQUEST_CODE && resultCode == PermissionsActivity.PERMISSIONS_DENIED) {
            finish();
        }

    }

    /**
     * 记住账号
     *
     * @param phone
     */
    public void onShared(String phone, String pwd) {
        boolean CheckBoxLogin = checkboxLgoin.isChecked();
        if (CheckBoxLogin) {
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("uname", phone);
            editor.putString("pwd", pwd);
            editor.putBoolean("checkboxBoolean", true);
            editor.commit();
        } else {
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("uname", null);
            editor.putString("pwd", pwd);
            editor.putBoolean("checkboxBoolean", false);
            editor.commit();
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            IsStringSPUtils.tianjia(entity);
            if (entity.getEventType() == UserPresenter.login_success) {
                PersonDataBean personBean = (PersonDataBean) entity.getData();
                FilterUtil.putSharePre(LoginActivity.this, personBean);
                SPUtils.put(this,SPUtils.DEFAULT_FILE_NAME,"auto_login_code",personBean.getAuto_login_code());
                FilterUtil.sendLoginSucceed(this);
                if(Main){
                    startActivity(new Intent(this, MainActivity.class));
                }
                finish();
                Intent intent1 = new Intent(LoginActivity.LOGIN);
                sendBroadcast(intent1);
                closeProgressDialog();
            }
        } else if (entity.getEventType() == UserPresenter.login_fail) {
            MAlert.alert(entity.getData(), Gravity.TOP);
            try {
                closeProgressDialog();
            } catch (Exception e) {
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }


}
